<template>
	<div class="default-main">

		<cus-table-title id="update-log-table-title" icon="local-aliIntl-catalog" label="更新日志">
			<template #after>
				<el-button v-if="hasPermission('sys-update-log:saveUpdateLog')" icon="el-icon-Plus" size="small" style="margin-left: 10px" type="primary"
				           @click="toAdd">发布
				</el-button>
			</template>
		</cus-table-title>

		<el-scrollbar :max-height="maxHeight!" class="scrollbar">
			<el-timeline v-loading="tableLoading">
				<el-card v-if="updateLogTableData.length === 0" class="text-center">暂无数据</el-card>
				<el-timeline-item v-for="(updateLog, index) of updateLogTableData" v-else :key="`updateLog_${index}`" :timestamp="formatDateTime(updateLog.releaseTime)"
				                  center placement="top">
					<el-card>
						<template v-if="updateLog.title" #header>
							{{ updateLog.title }}
						</template>
						<el-text class="content">{{ updateLog.content }}</el-text>
						<template v-if="hasPermission(['sys-update-log:saveUpdateLog', 'sys-update-log:deleteUpdateLog'])" #footer>
							<el-button v-auth="'sys-update-log:saveUpdateLog'" icon="el-icon-Edit" size="small" type="primary"
							           @click="toUpdate(updateLog)">编辑
							</el-button>
							<el-popconfirm :hide-after="0" :title="`确定要删除该更新日志（${formatDateTime(updateLog.releaseTime)}）吗？`" width="auto"
							               @confirm="remove(updateLog)">
								<template #reference>
									<el-button v-auth="'sys-update-log:deleteUpdateLog'" icon="el-icon-Delete" size="small" type="danger">删除</el-button>
								</template>
							</el-popconfirm>
						</template>
					</el-card>
				</el-timeline-item>
			</el-timeline>
		</el-scrollbar>

		<cus-pagination id="update-log-pagination" ref="pageRef" v-model="updateLogTableData" v-model:loading="tableLoading" :pageSize="10" :params="params"
		                class="pagination" show-refresh url="/system/sys-update-log/readOnly/pageUpdateLog"/>

		<!-- 对话框（新增、修改） -->
		<el-dialog v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="true" :title="dialogTitle" append-to-body center class="cus-dialog"
		           destroy-on-close draggable width="50%">
			<el-form ref="editFormRef" :model="updateLog" :rules="rules" label-width="auto">
				<el-form-item label="标题" prop="title">
					<el-input v-model="updateLog.title" clearable/>
				</el-form-item>
				<el-form-item label="发布时间" prop="releaseTime">
					<el-date-picker v-model="updateLog.releaseTime" type="datetime"/>
				</el-form-item>
				<el-form-item label="内容" prop="content">
					<el-input v-model="updateLog.content" :autosize="{ minRows: 10, maxRows: 30}" clearable type="textarea"/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button v-auth="'sys-update-log:saveUpdateLog'" icon="el-icon-CircleCheck" type="primary" @click="save">
					保存
				</el-button>
				<el-button icon="el-icon-CircleClose" type="warning" @click="dialogVisible = false">
					取消
				</el-button>
			</template>
		</el-dialog>

	</div>
</template>

<script lang="ts" name="UpdateLog" setup>

import CusPagination from '@/components/cus-pagination.vue'
import {focusFormErrorElement, formatDateTime, messageSuccess} from '@/utils/commonUtil'
import {useUserStore} from '@/stores/modules/user.store'
import {nextTick, onMounted, reactive, ref} from 'vue'
import {debounce, type DebouncedFunc} from 'lodash-es'
import {calcMaxHeight} from '@/utils/layoutUtil'
import {useEventListener} from '@vueuse/core'
import CusTableTitle from '@/components/cus-table-title.vue'
import {type FormInstance, type FormRules} from 'element-plus'
import {hasPermission} from '@/utils/authUtil'
import {deleteUpdateLogApi, saveUpdateLogApi} from '@/api/system/updateLog.api'

const userStore = useUserStore()

const editFormRef = ref<FormInstance>()
const pageRef = ref()

const tableLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const updateLogTableData = ref<SysUpdateLog[]>([])
const params = reactive({
	operator_eq: userStore.username
})
const maxHeight = ref<number>()

const updateLog = reactive<SysUpdateLog>({
	id: undefined,
	title: undefined,
	content: undefined,
	releaseTime: undefined,
	operator: undefined,
	createTime: undefined,
	updateTime: undefined
})

const rules = reactive<FormRules>({
	title: [
		{required: false, max: 100, message: '不超过 100 个字符', trigger: 'change', type: 'string'}
	],
	content: [
		{required: true, message: '请输入内容', trigger: 'change'},
		{max: 5000, message: '不超过 5000 个字符', trigger: 'change'}
	],
	releaseTime: [
		{required: true, message: '请选择发布时间', trigger: 'change', type: 'date'}
	]
})

/**
 * 计算最大高度
 */
const getMaxHeight: DebouncedFunc<() => typeof getMaxHeight> = debounce(() => {
	maxHeight.value = calcMaxHeight('#update-log-table-title', '#update-log-pagination')
	return getMaxHeight
}, 100, {
	leading: true,
	trailing: false,
	maxWait: 100
})

const resetUpdateLog = () => {
	for (const key in updateLog) {
		updateLog[<keyof SysUpdateLog>key] = undefined
	}
}

const toAdd = () => {
	resetUpdateLog()
	updateLog.releaseTime = new Date()
	dialogTitle.value = '新增更新日志'
	dialogVisible.value = true
}

const toUpdate = (row: SysUpdateLog) => {
	resetUpdateLog()
	Object.assign(updateLog, row)
	dialogTitle.value = '编辑更新日志'
	dialogVisible.value = true
}

const save = () => {
	editFormRef.value?.validate((isValid: boolean) => {
		if (isValid) {
			const request: SaveUpdateLogRequest = {
				id: updateLog.id,
				title: updateLog.title,
				content: updateLog.content!,
				releaseTime: updateLog.releaseTime!
			}
			saveUpdateLogApi(request).then(() => {
				dialogVisible.value = false
				messageSuccess(request.id ? '已更新' : '已发布')
				pageRef.value.reload()
			})
		} else {
			focusFormErrorElement()
		}
	})
}

const remove = (row: SysUpdateLog) => {
	deleteUpdateLogApi(row.id!).then(() => {
		messageSuccess('已删除')
		pageRef.value.reload()
	})
}

onMounted(() => {
	nextTick(() => {
		useEventListener(window, 'resize', getMaxHeight()!)
	})
})

</script>

<style lang="scss" scoped>
.scrollbar {
	padding-right: 10px;
	width: 75%;
	margin: 0 auto;
}

.pagination {
	width: 75%;
	margin: 10px auto 0 auto;
}

.content {
	white-space: pre-wrap;
	line-height: 1.6em;
}
</style>
